/**
 * 
 */
package com.uploadservice;


import java.io.File;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.Data.GeoTag;
import com.Managers.DirManagerClass;
import com.Managers.PictureManagerClass;
import com.SoapClasses.SoapPost;
import com.shareup.R;


/**
 * @author Chris
 * 
 */
public class UploadService extends Service {

    private static final int myID = 1433;

    private static int position;

    private static final String PREF_NAME = "SERVICEUPLOAD";

    private boolean[] coverList;

    public static void deletePosition(Context context) {

        Log.e("step 11", "clear...");
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();

        // deleting cache
        DirManagerClass.deleteUploadCache();

    }

    private int albumIndex;

    private String comment;

    private boolean hasGeotag;

    private int idOwner;

    private int idUser;

    private GeoTag location;

    private NotificationManager nManager;

    private String[] pathList;

    private PendingIntent pi;

    private int privacyIndex;

    private SoapPost sp;

    private String tags;

    /*
     * (non-Javadoc)
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {

        Log.e("step 1", "entered to create");
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    }

    @Override
    public void onDestroy() {

        // SAVE THE ACTUAL POSITION
        savePosition();
        super.onDestroy();
    }

    @Override
    public void onLowMemory() {

        // SAVE THE ACTUAL POSITION
        savePosition();
        super.onLowMemory();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.e("step 2", "entered to onstart");
        onHandleIntent(intent);
        return START_STICKY;
    }

    private void exit() {

        Log.e("step 10", "ending...");
        deletePosition(this);
        Log.e("step 12", "ended");
        this.stopForeground(true);
        updateNotification(true);
    }

    private void sendData() {

        new Thread(new Runnable() {

            @Override
            public void run() {

                for (String fl : pathList) {

                    if (fl != null) {
                        try {

                            String[] dataup = new String[10];

                            if (hasGeotag) {

                                dataup = new String[15];
                                dataup[10] = String.valueOf(location.getLatitude());
                                dataup[11] = String.valueOf(location.getLongitude());
                                dataup[12] = location.getAddress();
                                dataup[13] = location.getCity();
                                dataup[14] = location.getCountry();

                            }

                            if (comment.length() > 0)
                                dataup[0] = URLEncoder.encode(comment, "UTF-8");
                            else
                                dataup[0] = "";

                            dataup[1] = String.valueOf(idOwner);
                            dataup[2] = String.valueOf(idUser);
                            dataup[3] = "2";
                            dataup[4] = "";
                            dataup[5] = String.valueOf(albumIndex);
                            dataup[6] = String.valueOf(privacyIndex);
                            dataup[7] = "";
                            dataup[8] = "";
                            dataup[9] = "";

                            File file = new File(fl);
                            Log.e("sendData", "veryfing file: " + fl);
                            // CONTINUE ONLY IF THE FILE EXISTS
                            if (file.exists()) {
                                Log.e("sendData", "file exists: true");
                                // SETTING WIDTH AND HEIGHT
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inJustDecodeBounds = true;
                                BitmapFactory.decodeFile(fl, options);
                                int wth = options.outWidth;
                                int hth = options.outHeight;
                                long lenght = file.length();
                                // END W AND H

                                byte[] pic = PictureManagerClass.getBytesFromFile(file);
                                Log.e("picLength", pic.length + "");
                                file = null;
                                // SETTING
                                // 4 BASE64
                                // 7 W
                                // 8 H
                                // 9 L
                                dataup[4] = String.valueOf(coverList[position]);
                                dataup[7] = String.valueOf(wth);
                                dataup[8] = String.valueOf(hth);
                                dataup[9] = String.valueOf(lenght);
                                Log.e("step 7", "uploading... " + fl);
                                // SET THE CURRENT ITEM AS UPLOADED
                                pathList[position] = null;
                                // SAVE THE ACTUAL POSITION
                                savePosition();
                                String mes = sp.uploadPicture(dataup, tags, SoapPost.UPLOAD_PICTURE, pic);
                                Log.e("picID", mes);
                                pic = null;
                                dataup = null;
                                position++;
                                updateNotification(false);

                                Thread.sleep(1 * 1000);

                            }// END FILE EXISTS

                        }
                        catch (Exception ex) {
                            // SAVE THE ACTUAL POSITION
                            savePosition();
                            //
                            StackTraceElement[] stack = ex.getStackTrace();
                            String Trace = " ";
                            for (StackTraceElement line : stack) {
                                Trace += line.toString();
                            }
                            Log.e("SERVICE: ", Trace);
                        }

                    }// END FL NULL

                }// END FOR

                exit();
            }
        }).start();;

    }

    private void updateNotification(boolean completed) {

        Log.e("step 8", "updating notification");
        String ticker = String.format(getResources().getString(R.string.upload_uploading_tick), position);
        String message = String.format(getResources().getString(R.string.upload_uploading_message_progress), position, pathList.length);
        String title = String.format(getResources().getString(R.string.upload_uploading_title), position);
        String title_completed = getResources().getString(R.string.upload_uploading_title_completed);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentText(message);
        builder.setTicker(ticker);
        builder.setSmallIcon(R.drawable.ic_upload_tick);
        builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_action_upload));
        if (!completed)
            builder.setContentTitle(title);
        else {
            builder.setSmallIcon(R.drawable.done_menu_icon);
            builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.done_menu_icon));
            builder.setContentTitle(title_completed);
            pi = PendingIntent.getActivity(this, 0, new Intent(), 0);

        }
        builder.setContentIntent(pi);

        if (completed) {

            nManager.notify(myID, builder.build());
        }

        else {
            Notification notf = builder.build();
            notf.flags = Notification.FLAG_ONGOING_EVENT;
            startForeground(myID, builder.build());
        }

    }

    protected void onHandleIntent(Intent data) {

        Log.e("step 3", "entered to handle");
        // GETS THE POSITIONS IF THE SERVICE WAS STOPPED BEFORE
        // RETURN 0 IF IT WASNT
        getPosition();
        //
        if (data == null || data.getExtras() == null)
            this.stopForeground(true);
        else {

            Bundle dt = data.getExtras();

            tags = dt.getString("tags");
            pathList = dt.getStringArray("pathList");
            coverList = dt.getBooleanArray("coverList");
            hasGeotag = dt.getBoolean("hasGeotag");

            if (hasGeotag) {

                location = new GeoTag();
                location.setLatitude(dt.getDouble("latitude"));
                location.setLongitude(dt.getDouble("longitude"));
                location.setAddress(dt.getString("address"));
                location.setCity(dt.getString("city"));
                location.setCountry(dt.getString("country"));

            }
            idOwner = dt.getInt("idOwner");
            idUser = dt.getInt("idUser");
            albumIndex = dt.getInt("albumindex");
            privacyIndex = dt.getInt("privacyindex");
            comment = dt.getString("comment");

            sp = new SoapPost();

            // CREATES THE NOTFICATION
            createNotification();
            // FINALLY SEND THE DATA TO THE WEB SERVICE
            sendData();
        }

    }

    void createNotification() {

        Log.e("step 4", "entered to create notification");
        // In this sample, we'll use the same text for the ticker and the
        // expanded notification
        CharSequence text = getText(R.string.upload_waiting);
        //
        pi = PendingIntent.getActivity(this, 0, new Intent(), Notification.FLAG_FOREGROUND_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_upload_tick);
        builder.setTicker(text);
        builder.setContentIntent(pi);
        builder.setContentText(text);
        builder.setContentTitle(text);
        builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_action_upload));
        nManager.notify(myID, builder.build());
    }

    void getPosition() {

        SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        position = prefs.getInt("position", 0);
        Log.e("step 3.1", position + "");
        Set<String> set = new HashSet<String>();
        set = prefs.getStringSet("pathList", set);

        int pos = 0;
        for (String path : set) {
            pathList = new String[set.size()];
            pathList[pos] = path;
            pos++;
        }

    }

    void savePosition() {

        Log.e("step 9", "saving position");
        // SET THE VALUES FROM PATHS TO SET TO SAVE IT INTO PREFERENCES
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("position", position);
        Set<String> set = new HashSet<String>();
        if (pathList != null) {
            for (int i = 0; i < position; i++)
                pathList[i] = null;

            for (int i = position; i < pathList.length; i++)
                if (pathList[i] != null)
                    set.add(pathList[i]);
        }

        if (pathList != null)
            editor.putStringSet("pathList", set);
        editor.commit();
    }

}
